package net.lovesrc.support.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public abstract class JdbcTemplateSupport {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    public JSONObject queryForRow(JdbcTemplate jdbcTemplate, String sql, Object... args) {
        try {
            Map<String, Object> row = jdbcTemplate.queryForMap(sql, args);
            return toJsonObject(row);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    public <T> T findOne(JdbcTemplate jdbcTemplate, Class<T> clz, String sql, Object... args) {
        JSONObject row = queryForRow(jdbcTemplate, sql, args);
        if (row == null) {
            return null;
        }
        return JSON.toJavaObject(row, clz);
    }

    //todo
    public List<JSONObject> queryForRows(JdbcTemplate jdbcTemplate, String sql, Object... args) {
        List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql, args);
        return rows
                .stream()
                .map(r -> toJsonObject(r))
                .collect(Collectors.toList());
    }

    public JSONObject toJsonObject(Object origin) {
        return JSON.parseObject(JSON.toJSONString(origin));
    }

    public void insertRow(JdbcTemplate jdbcTemplate, String tableName, JSONObject row) {
        StringBuilder sql = new StringBuilder("insert into " + tableName + "(");
        List<String> keys = Lists.newArrayList();
        List<Object> values = Lists.newArrayList();
        for (String key : row.keySet()) {
            keys.add(key);
            values.add(row.getObject(key, Object.class));
        }
        sql.append(StringUtils.join(keys, ","))
                .append(") values(")
                .append(StringUtils.repeat("?", ",", keys.size()))
                .append(")");
        jdbcTemplate.update(sql.toString(), values.toArray(new Object[values.size()]));
    }

    public void insertLogRow(JdbcTemplate jdbcTemplate, String tableName, JSONObject row) {
        try {
            insertRow(jdbcTemplate, tableName, row);
        } catch (Exception e) {
            logger.error("insert log row error, {}", e.getMessage());
        }
    }

    public void updateRow(JdbcTemplate jdbcTemplate, String tableName, JSONObject sets, String whereCondition, Object... args) {
        StringBuilder sql = new StringBuilder("update " + tableName + " set ");
        List<String> setsSql = Lists.newArrayList();
        List<Object> values = Lists.newArrayList();
        for (String key : sets.keySet()) {
            setsSql.add(key + " = ?");
            values.add(sets.getObject(key, Object.class));
        }
        if (args.length > 0) {
            values.addAll(Lists.newArrayList(args));
        }
        sql.append(StringUtils.join(setsSql, ","))
                .append(" where ").append(whereCondition);
        jdbcTemplate.update(sql.toString(), values.toArray(new Object[values.size()]));
    }

}
